package com.spa.infrastructure.repository.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.spa.infrastructure.repository.condition.UserCollectionRefCondition;
import com.spa.infrastructure.repository.mapper.UserCollectionRefMapper;
import com.spa.infrastructure.repository.po.UserCollectionRefPO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class UserCollectionRepositoryService extends MPJBaseServiceImpl<UserCollectionRefMapper, UserCollectionRefPO> {

    public List<UserCollectionRefPO> listInfo(UserCollectionRefCondition condition) {
        return list(wrapper(condition));
    }

    public List<UserCollectionRefPO> listInfoByUserId(Long userId) {
        UserCollectionRefCondition condition = new UserCollectionRefCondition();
        condition.setUserId(userId);
        return list(wrapper(condition));
    }

    private LambdaQueryWrapper<UserCollectionRefPO> wrapper(UserCollectionRefCondition condition) {
        LambdaQueryWrapper<UserCollectionRefPO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ObjectUtils.isNotEmpty(condition.getId()),UserCollectionRefPO::getId,condition.getId());
        wrapper.eq(ObjectUtils.isNotEmpty(condition.getUserId()),UserCollectionRefPO::getUserId,condition.getUserId());
        wrapper.eq(ObjectUtils.isNotEmpty(condition.getMassagistId()),UserCollectionRefPO::getMassagistId,condition.getMassagistId());
        return wrapper;
    }

    public boolean delInfoByUserIdAndMassagist(Long userId,Long massagistId) {
        LambdaQueryWrapper<UserCollectionRefPO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserCollectionRefPO::getUserId,userId);
        wrapper.eq(UserCollectionRefPO::getMassagistId,massagistId);
        return remove(wrapper);
    }

    public long countCollectionByMassagistId(Long massagistId) {
        UserCollectionRefCondition condition = new UserCollectionRefCondition();
        condition.setMassagistId(massagistId);
        return count(wrapper(condition));
    }

    public List<Map<String, Object>> countByMassagistIds(List<Long> ids) {
        return baseMapper.selectMaps(countWrapper(ids));
    }

    private QueryWrapper<UserCollectionRefPO> countWrapper(List<Long> ids) {
        QueryWrapper<UserCollectionRefPO> countWrapper = new QueryWrapper<>();
        countWrapper.groupBy("massagist_id");
        countWrapper.select("massagist_id","count(id) count");
        countWrapper.in(CollectionUtil.isNotEmpty(ids), "massagist_id", ids);
        return countWrapper;
    }
}
